
package jp.isisredirect.h2h;

import java.nio.ByteBuffer;
import java.util.Map;

import jp.isisredirect.adk.ADKBaseActivity;
import jp.isisredirect.bluetooth.BluetoothChatService;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.widget.Button;
import android.view.View.OnClickListener;

public class H2hActivity extends ADKBaseActivity implements OnClickListener {

    static final String TAG = "H2hActivity";
    static final String ACTION_USB_PERMISSION = "jp.isisredirect.h2h.action.USB_PERMISSION";

    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
    private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
    private static final int REQUEST_ENABLE_BT = 3;

    // Local Bluetooth adapter
    private BluetoothAdapter mBluetoothAdapter = null;
    // Member object for the chat services
    private BluetoothChatService mChatService = null;
    // Name of the connected device
    private String mConnectedDeviceName = null;

    private static final String VIBRATION = "vibration";
    private static final String LOOPBACK = "loopback";
    private static final String LOOPBACKVIBRATION = "loopbackvibration";
    private boolean mVibration = true;
    private boolean mLoopback = false;
    private boolean mLoopbackVibration = false;

    private TextView mRightTitle;
    private TextView mMidTitle;
    private TextView mTVInterval;
    private TextView mTVEpulsecount;
    private TextView mTVPulsecount;
    private TextView mTVBreathInterval;
    private TextView mTVEBreathcount;
    private TextView mTVBreathcount;
    private TextView mTVYInterval;
    private TextView mTVYEpulsecount;
    private TextView mTVYPulsecount;
    private TextView mTVYBreathInterval;
    private TextView mTVYEBreathcount;
    private TextView mTVYBreathcount;
    private Button mResetButton;

    // h2h command
    private static final byte H2H_RESET = 0x51;
    private static final byte H2H_PULSE = 0x61;
    private static final byte H2H_BREATH = 0x67;

    public H2hActivity() {
        super(ACTION_USB_PERMISSION);
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = sp.edit();
        Map<String, ?> keys = sp.getAll();
        if (keys.size() == 0) {
            editor.putBoolean(VIBRATION, mVibration);
            editor.putBoolean(LOOPBACK, mLoopback);
            editor.putBoolean(LOOPBACKVIBRATION, mLoopbackVibration);
            editor.commit();
        } else {
            mVibration = sp.getBoolean(VIBRATION, mVibration);
            mLoopback = sp.getBoolean(LOOPBACK, mLoopback);
            mLoopbackVibration = sp.getBoolean(LOOPBACKVIBRATION, mLoopbackVibration);
        }

        // Set up the custom title
        TextView lefttitle = (TextView) findViewById(R.id.title_left_text);
        lefttitle.setText(R.string.app_name);
        mRightTitle = (TextView) findViewById(R.id.title_right_text);
        mRightTitle.setText(R.string.title_not_connected);
        mMidTitle = (TextView) findViewById(R.id.title_mid_text);
        mMidTitle.setText(R.string.title_not_connected_adk);

        //
        mTVInterval = (TextView) findViewById(R.id.interval);
        mTVEpulsecount = (TextView) findViewById(R.id.epulsecount);
        mTVPulsecount = (TextView) findViewById(R.id.pulsecount);
        mTVBreathInterval = (TextView) findViewById(R.id.breathinterval);
        mTVEBreathcount = (TextView) findViewById(R.id.ebreathcount);
        mTVBreathcount = (TextView) findViewById(R.id.breathcount);
        mTVYInterval = (TextView) findViewById(R.id.yinterval);
        mTVYEpulsecount = (TextView) findViewById(R.id.yepulsecount);
        mTVYPulsecount = (TextView) findViewById(R.id.ypulsecount);
        mTVYBreathInterval = (TextView) findViewById(R.id.ybreathinterval);
        mTVYEBreathcount = (TextView) findViewById(R.id.yebreathcount);
        mTVYBreathcount = (TextView) findViewById(R.id.ybreathcount);

        // reset button
        mResetButton = (Button) findViewById(R.id.button_reset);
        mResetButton.setOnClickListener(this);

        // for BlueTooth
        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }

    }

    @Override
    public void onStart() {
        super.onStart();
        Log.e(TAG, "++ ON START ++");

        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            // Otherwise, setup the chat session
        } else {
            if (mChatService == null)
                setupChat();
        }
    }

    @Override
    public synchronized void onResume() {
        super.onResume();
        Log.e(TAG, "+ ON RESUME +");

        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity
        // returns.
        if (mChatService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't
            // started already
            if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
                // Start the Bluetooth chat services
                mChatService.start();
            }
        }
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        mVibration = sp.getBoolean(VIBRATION, mVibration);
        mLoopback = sp.getBoolean(LOOPBACK, mLoopback);
        mLoopbackVibration = sp.getBoolean(LOOPBACKVIBRATION, mLoopbackVibration);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Stop the Bluetooth chat services
        if (mChatService != null)
            mChatService.stop();
        Log.e(TAG, "--- ON DESTROY ---");
    }

    // ADK connection events
    @Override
    protected void onADKConnected() {
        mMidTitle.setText(R.string.title_connected_adk);
    }

    @Override
    protected void onADKDisconnected() {
        mMidTitle.setText(R.string.title_not_connected_adk);
    }

    // ADK data receive event
    @Override
    protected void onADKReceived(ByteBuffer buffer) {
        if (7 == buffer.limit()) {
            // show my heart data
            buffer.flip();
            byte hcode = buffer.get();
            switch (hcode) {
                case H2H_PULSE: {
                    short interval = buffer.getShort();
                    String str_interval = String.valueOf(interval);
                    mTVInterval.setText(str_interval);
                    short estimate_pc = buffer.getShort();
                    String str_estimate_pc = String.valueOf(estimate_pc);
                    mTVEpulsecount.setText(str_estimate_pc);
                    short pc = buffer.getShort();
                    String str_pc = String.valueOf(pc);
                    mTVPulsecount.setText(str_pc);

                    // send to pier
                    byte[] b = new byte[buffer.limit()];
                    buffer.flip();
                    buffer.get(b);
                    sendBTMessage(b);

                    // loopback
                    if (mLoopback) {
                        sendADKData(buffer);
                    }
                    if (mLoopbackVibration) {
                        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
                        vibrator.vibrate(100);
                    }
                }
                    break;
                case H2H_BREATH: {
                    short interval = buffer.getShort();
                    String str_interval = String.valueOf(interval);
                    mTVBreathInterval.setText(str_interval);
                    short estimate_pc = buffer.getShort();
                    String str_estimate_pc = String.valueOf(estimate_pc);
                    mTVEBreathcount.setText(str_estimate_pc);
                    short pc = buffer.getShort();
                    String str_pc = String.valueOf(pc);
                    mTVBreathcount.setText(str_pc);

                    // send to pier
                    byte[] b = new byte[buffer.limit()];
                    buffer.flip();
                    buffer.get(b);
                    sendBTMessage(b);

                    // loopback
                    if (mLoopback) {
                        sendADKData(buffer);
                    }
                    if (mLoopbackVibration) {
                        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
                        vibrator.vibrate(100);
                    }
                }
                    break;
            }
        }
    }

    // for BlueTooth
    // The Handler that gets information back from the BluetoothChatService
    private final Handler mBTHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case BluetoothChatService.MESSAGE_STATE_CHANGE:
                    Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                    switch (msg.arg1) {
                        case BluetoothChatService.STATE_CONNECTED:
                            // depend on UI
                            mRightTitle.setText(R.string.title_connected_to);
                            mRightTitle.append(mConnectedDeviceName);
                            break;
                        case BluetoothChatService.STATE_CONNECTING:
                            // depend on UI
                            mRightTitle.setText(R.string.title_connecting);
                            break;
                        case BluetoothChatService.STATE_LISTEN:
                        case BluetoothChatService.STATE_NONE:
                            // depend on UI
                            mRightTitle.setText(R.string.title_not_connected);
                            break;
                    }
                    break;
                case BluetoothChatService.MESSAGE_WRITE: // outgoing
                    // byte[] writeBuf = (byte[]) msg.obj;
                    break;
                case BluetoothChatService.MESSAGE_READ: // incoming
                    byte[] readBuf = (byte[]) msg.obj;
                    Log.i(TAG, "MESSAGE_READ: " + msg.arg1);
                    if (msg.arg1 == 7) {
                        ByteBuffer rec_buffer = ByteBuffer.allocate(msg.arg1);
                        rec_buffer.put(readBuf, 0, msg.arg1);
                        rec_buffer.flip();
                        byte hcode = rec_buffer.get();
                        switch (hcode) {
                        // case H2H_RESET:
                        // {
                        //
                        // }
                        // break;
                            case H2H_PULSE:
                            {
                                // show your heart data
                                short interval = rec_buffer.getShort();
                                String str_interval = String.valueOf(interval);
                                mTVYInterval.setText(str_interval);
                                short estimate_pc = rec_buffer.getShort();
                                String str_estimate_pc = String.valueOf(estimate_pc);
                                mTVYEpulsecount.setText(str_estimate_pc);
                                short pc = rec_buffer.getShort();
                                String str_pc = String.valueOf(pc);
                                mTVYPulsecount.setText(str_pc);

                                // send to ADK board
                                sendADKData(rec_buffer);

                                // vibrate
                                if (mVibration) {
                                    Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
                                    vibrator.vibrate(100);
                                }
                            }
                                break;
                            case H2H_BREATH:
                            {
                                // show your heart data
                                short interval = rec_buffer.getShort();
                                String str_interval = String.valueOf(interval);
                                mTVYBreathInterval.setText(str_interval);
                                short estimate_pc = rec_buffer.getShort();
                                String str_estimate_pc = String.valueOf(estimate_pc);
                                mTVYEBreathcount.setText(str_estimate_pc);
                                short pc = rec_buffer.getShort();
                                String str_pc = String.valueOf(pc);
                                mTVYBreathcount.setText(str_pc);

                                // send to ADK board
                                sendADKData(rec_buffer);

                                // vibrate
                                if (mVibration) {
                                    Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
                                    vibrator.vibrate(100);
                                }
                            }
                                break;
                        }
                    }

                    break;
                case BluetoothChatService.MESSAGE_DEVICE_NAME:
                    // depend on UI
                    // save the connected device's name
                    mConnectedDeviceName = msg.getData()
                            .getString(BluetoothChatService.DEVICE_NAME);
                    break;
                case BluetoothChatService.MESSAGE_TOAST:
                    // depend on UI
                    Toast.makeText(getApplicationContext(),
                            msg.getData().getString(BluetoothChatService.TOAST),
                            Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private void setupChat() {
        Log.d(TAG, "setupChat()");
        // Initialize the BluetoothChatService to perform bluetooth connections
        mChatService = new BluetoothChatService(this, mBTHandler);
    }

    private void ensureDiscoverable() {
        Log.d(TAG, "ensure discoverable");
        if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }

    private void connectDevice(Intent data, boolean secure) {
        // Get the device MAC address
        String address = data.getExtras()
                .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
        // Get the BLuetoothDevice object
        // BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        // Attempt to connect to the device
        mChatService.connect(address, secure);
    }

    /**
     * Sends a message.
     * 
     * @param message A string of text to send.
     */
    private void sendBTMessage(byte[] message) {
        // Check that we're actually connected before trying anything
        if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
            // Toast.makeText(this, R.string.not_connected,
            // Toast.LENGTH_SHORT).show();
            return;
        }

        // Check that there's actually something to send
        if (message.length > 0) {
            // Get the message bytes and tell the BluetoothChatService to write
            mChatService.write(message);
        }
    }

    // for control
    @Override
    protected void setContentViewByRes() {
        // Set up the window layout
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.main);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
    }

    // Option menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.option_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent serverIntent = null;
        switch (item.getItemId()) {
            case R.id.secure_connect_scan:
                // Launch the DeviceListActivity to see devices and do scan
                serverIntent = new Intent(this, DeviceListActivity.class);
                startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
                return true;
            case R.id.insecure_connect_scan:
                // Launch the DeviceListActivity to see devices and do scan
                serverIntent = new Intent(this, DeviceListActivity.class);
                startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
                return true;
            case R.id.discoverable:
                // Ensure this device is discoverable by others
                ensureDiscoverable();
                return true;
            case R.id.preference:
                // Launch the PreferenceActivity
                serverIntent = new Intent(this, MyPreferenceActivity.class);
                startActivity(serverIntent);
                return true;
        }
        return false;
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "onActivityResult " + resultCode);
        switch (requestCode) {
            case REQUEST_CONNECT_DEVICE_SECURE:
                // When DeviceListActivity returns with a device to connect
                if (resultCode == Activity.RESULT_OK) {
                    connectDevice(data, true);
                }
                break;
            case REQUEST_CONNECT_DEVICE_INSECURE:
                // When DeviceListActivity returns with a device to connect
                if (resultCode == Activity.RESULT_OK) {
                    connectDevice(data, false);
                }
                break;
            case REQUEST_ENABLE_BT:
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK) {
                    // Bluetooth is now enabled, so set up a chat session
                    setupChat();
                } else {
                    // User did not enable Bluetooth or an error occured
                    Log.d(TAG, "BT not enabled");
                    Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT)
                            .show();
                    finish();
                }
                break;
        }
    }

    public void onClick(View v) {
        if (v == mResetButton) {
            ByteBuffer buffer = ByteBuffer.allocate(1);
            buffer.put(H2H_RESET);
            this.sendADKData(buffer);
        }
    }
}
